package com.example.dubbo.account.dubbo;

import com.alibaba.fastjson.JSON;
import com.example.dubbo.account.service.AccountTblService;
import com.example.dubbo.api.dto.AccountDTO;
import com.example.dubbo.api.response.ObjectResponse;
import com.example.dubbo.api.dubbo.AccountService;
import io.seata.core.context.RootContext;
import org.apache.dubbo.config.annotation.DubboService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.math.BigDecimal;

/**
 * Please add the follow VM arguments:
 * <pre>
 *     -Djava.net.preferIPv4Stack=true
 * </pre>
 * @author Liyuhang
 */
@DubboService(version = "1.0.0",protocol = "${dubbo.protocol.id}",
        application = "${dubbo.application.id}",registry = "${dubbo.registry.id}",
        timeout = 3000)
public class AccountServiceImpl implements AccountService {

    private static final Logger LOGGER = LoggerFactory.getLogger(AccountService.class);

    @Autowired
    private AccountTblService accountTblService;


    @Override
    public ObjectResponse debit(String userId, int money) {
        LOGGER.info("Account Service ... xid: " + RootContext.getXID());
        LOGGER.info("Deducting balance SQL: update account_tbl set money = money - {} where user_id = {}",money,userId);
        AccountDTO accountDTO = new AccountDTO();
        accountDTO.setAmount(BigDecimal.valueOf(money)).setUserId(userId);
        ObjectResponse response = accountTblService.decreaseAccount(accountDTO);
        LOGGER.info("Account Service End ... {}",JSON.toJSONString(response));
        return response;
    }
}
